//
//  WBRefreshControl.m
//  weibo110
//
//  Created by 臧松 on 16/1/12.
//  Copyright © 2016年 臧松. All rights reserved.
//
#define WBRefreshcontrolOffset -60
#import "WBRefreshControl.h"
#import "WBRefreshView.h"
#import "Masonry.h"
@interface WBRefreshControl ()

@property (nonatomic,strong) WBRefreshView * refreshView;

@end

@implementation WBRefreshControl

-(WBRefreshView *)refreshView{
    if (_refreshView == nil) {
        _refreshView = [WBRefreshView refreshView];
    }
    return _refreshView;
}
-(void)endRefreshing{
    [super endRefreshing];
    // 停止播放动画
    [self.refreshView stopAnimation];
}
-(void)beginRefreshing{
    [super beginRefreshing];
    
    [self.refreshView startAnimation];
}
-(instancetype)init{
    if (self = [super init]) {
        
        [self setupUI];
    }
    return self;
}
-(void)setupUI{
    // 设置 tintColor
    self.tintColor = [UIColor clearColor];
    // 添加控件
    [self addSubview:self.refreshView];
    // 自动布局
    [self.refreshView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY);
        make.size.mas_equalTo(self.refreshView.bounds.size);
    }];
    // 使用 KVO 监听位置变化
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
    });
    
    
}
// 删除 kvo
-(void)dealloc{
    
    [self removeObserver:self forKeyPath:@"frame"];
}

// kvo 监听方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    
    if (self.frame.origin.y > 0) {
        return;
    }
    // 判断是否正在刷新
    if (self.refreshing) {
        [self.refreshView startAnimation];
        return;
    }
    if (self.frame.origin.y<WBRefreshcontrolOffset && !self.refreshView.rotateFlag) {
        NSLog(@"反过来");
        self.refreshView.rotateFlag = YES;
    }else if((self.frame.origin.y >=WBRefreshcontrolOffset) && self.refreshView.rotateFlag){
        NSLog(@"转过去");
        self.refreshView.rotateFlag = NO;
    }
}
@end
